import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { passWord } from '@/api/config'
import { storage } from '@/utils/utils'
let historyPush: (...p: any) => void = () => {}
function passModeHandle() {
  const code = passWord.split('')
  document.addEventListener('keydown', bindCode)
  function bindCode(e: KeyboardEvent) {
    isCode(e.key)
  }
  function isCode(e: string) {
    if (e === code[0]) {
      if (code.length === 1) {
        document.removeEventListener('keydown', bindCode)
        storage.set('passWord', passWord)
        alert('开启隐藏模式')
        historyPush('/manage')
      } else {
        code.shift()
      }
    } else {
      document.removeEventListener('keydown', bindCode)
    }
  }
}
passModeHandle()
export default withRouter(PassMode)
function PassMode({ history }: any) {
  useEffect(() => {
    historyPush = history.push
  }, [history.push])
  return <></>
}
export const passWordLogin = () => {
  return new Promise((resolve, _reject) => {
    let passWordStorage = storage.get('passWord')
    if(typeof passWordStorage ==='number'){
      passWordStorage = passWordStorage+''
    }
    if (passWord === passWordStorage) return resolve(undefined)
    const passwordInput = prompt()
    if (passwordInput !== passWord) {
      return window.location.replace('/')
    } else {
      storage.set('passWord', passWord)
      resolve(undefined)
    }
  })
}
